import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.launch
import models.UserRepository
import models.shared.UserUi
import models.user.UserEvent
import models.user.UserViewState

class UserViewModel(
    private val userRepository: UserRepository
) : BaseViewModel<UserViewState, UserEvent>(
    initialState = UserViewState()
) {
    override fun obtainEvent(event: UserEvent) {
        when (event) {
            is UserEvent.LoadUser -> if (viewState.user == null) loadUser()
            UserEvent.Logout -> {
                userRepository.logout()
            }
        }
    }

    private fun loadUser() {
        updateState { it.copy(loadingStatus = LoadingStatus.Loading) }
        viewModelScope.launch {
            userRepository.me()
                .onSuccess { u ->
                    updateState {
                        it.copy(
                            user = UserUi.from(u),
                            loadingStatus = LoadingStatus.FullyLoad
                        )
                    }
                }
                .onFailure { t ->
                    updateState {
                        it.copy(
                            loadingStatus = LoadingStatus.Error(t.message)
                        )
                    }
                }
        }
    }
}